package com.imooc.security.browser;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

import com.imooc.security.core.properties.SecurityConstants;
import com.imooc.security.core.properties.SecurityProperties;
import com.imooc.security.core.social.SocialController;
import com.imooc.security.core.social.support.SimpleResponse;
import com.imooc.security.core.social.support.SocialUserInfo;

/**
 * 5.9.12 重构9
 * 浏览器环境下与安全相关的服务
 *
 */
/**
 * 7.2.1 分析AnonymousAuthenticationFilter源码
 * AnonymousAuthenticationFilter 95 判断前面过滤器是否进行过身份认证。如果没有认证则创建一个默认的，authentication principle是一个字符串
 *
 * 7.2.2 分析FilterSecurityInterceptor源码
 * 访问localhost:8080/user
 * FilterSecurityInterceptor 90
 * FilterSecurityInterceptor 111
 * FilterSecurityInterceptor 124 beforeInvocation执行了授权判断逻辑，后面的过滤器实际上进到服务里面去了
 * AbstractSecurityInterceptor 196
 * DefaultFilterInvocationSecurityMetadataSource 92 读取配置的antMatcher访问权限规则
 * AbstractSecurityInterceptor 199
 * AbstractSecurityInterceptor 233 投票器决定是否通过，默认的是1个通过全通过affirmative
 * AffirmativeBased 62 循环所有的投票者，springsecurity3只有一个投票者
 * AbstractSecurityInterceptor 235 投票不过，抛出异常。交给ExceptionTranslationFilter处理
 * ExceptionTranslationFilter 132
 * ExceptionTranslationFilter 172 
 * ExceptionTranslationFilter 203 跳转到自定义没权限url /authentication/require
 * 
 * 访问localhost:8080/index.html 进行登录
 * 然后重新debug一次
 * AbstractSecurityInterceptor 199 ADMIN->ROLE_ADMIN的原因
 * AbstractSecurityInterceptor 233
 * AffirmativeBased 62
 */
@RestController
public class BrowserSecurityController extends SocialController {

	private Logger logger = LoggerFactory.getLogger(getClass());

	private RequestCache requestCache = new HttpSessionRequestCache();

	private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

	@Autowired
	private SecurityProperties securityProperties;

	@Autowired
	private ProviderSignInUtils providerSignInUtils;

	/**
	 * 当需要身份认证时，跳转到这里
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(SecurityConstants.DEFAULT_UNAUTHENTICATION_URL)
	@ResponseStatus(code = HttpStatus.UNAUTHORIZED)
	public SimpleResponse requireAuthentication(HttpServletRequest request, HttpServletResponse response)
			throws IOException {

		SavedRequest savedRequest = requestCache.getRequest(request, response);

		if (savedRequest != null) {
			String targetUrl = savedRequest.getRedirectUrl();
			logger.info("引发跳转的请求是:" + targetUrl);
			if (StringUtils.endsWithIgnoreCase(targetUrl, ".html")) {
				redirectStrategy.sendRedirect(request, response, securityProperties.getBrowser().getSignInPage());
			}
		}

		return new SimpleResponse("访问的服务需要身份认证，请引导用户到登录页");
	}

	/**
	 * 用户第一次社交登录时，会引导用户进行用户注册或绑定，此服务用于在注册或绑定页面获取社交网站用户信息
	 */
	@GetMapping(SecurityConstants.DEFAULT_SOCIAL_USER_INFO_URL)
	public SocialUserInfo getSocialUserInfo(HttpServletRequest request) {
		Connection<?> connection = providerSignInUtils.getConnectionFromSession(new ServletWebRequest(request));
		return buildSocialUserInfo(connection);
	}

}

/*import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

import com.imooc.security.core.properties.SecurityConstants;
import com.imooc.security.core.properties.SecurityProperties;
import com.imooc.security.core.support.SimpleResponse;
import com.imooc.security.core.support.SocialUserInfo;

*//**
 * 4.4.6 自定义安全控制类
 * @author qilongfei
 *
 *//*
@RestController
public class BrowserSecurityController {

	private Logger logger = LoggerFactory.getLogger(getClass());
	
	private RequestCache requestCache = new HttpSessionRequestCache();
	
	private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
	
	@Autowired
	private SecurityProperties securityProperties;
	
	@Autowired
	private ProviderSignInUtils providerSignInUtils;
	
	*//**
	 * 4.4.7 自定义登录跳转controller
	 * 当需要身份认证时跳转到这里
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException 
	 *//*
	// 4.12.6 8重构，常量规范化
	// @RequestMapping("/authentication/require")
	@RequestMapping(SecurityConstants.DEFAULT_UNAUTHENTICATION_URL)
	// 4.4.10 定义返回码
	@ResponseStatus(code = HttpStatus.UNAUTHORIZED)
	public SimpleResponse requireAuthentication(HttpServletRequest request,HttpServletResponse response) throws IOException{
		SavedRequest saveRequest = requestCache.getRequest(request, response);
		
		if(saveRequest!=null){
			// 引发认证跳转的初始url
			String targetUrl = saveRequest.getRedirectUrl();
			logger.info("引发跳转的请求是:"+ targetUrl);
			
			// 4.4.12 根据配置跳转
			if(StringUtils.endsWithIgnoreCase(targetUrl, ".html")){
				redirectStrategy.sendRedirect(request, response, securityProperties.getBrowser().getSignInPage());
			}
		}
		
		return new SimpleResponse("访问的服务需要身份认证，请引导用户到登录页");
	}
	
	*//**
	 * 5.6.10 返回社交用户信息的控制器，用于社交注册页显示用户信息
	 *//*
	@GetMapping("/social/user")
	public SocialUserInfo getSocialInfo(HttpServletRequest request){
		SocialUserInfo userInfo = new SocialUserInfo();
		Connection<?> connection = providerSignInUtils.getConnectionFromSession(new ServletWebRequest(request));
		userInfo.setProviderId(connection.getKey().getProviderId());
		userInfo.setProviderUserId(connection.getKey().getProviderUserId());
		userInfo.setNickname(connection.getDisplayName());
		userInfo.setHeadimg(connection.getImageUrl());
		return userInfo;
	}
	
	*//**
	 * 5.9.4 session失效控制器
	 *//*
	@GetMapping("/session/invalid")
	@ResponseStatus(code = HttpStatus.UNAUTHORIZED)
	public SimpleResponse sessionInvalid(){
		String message = "session失效";
		return new SimpleResponse(message);
	}
}*/
